package com.charles.engine;

import com.alibaba.cola.statemachine.builder.StateMachineBuilder;
import com.alibaba.cola.statemachine.builder.StateMachineBuilderFactory;
import com.charles.enums.ChannelTypeEnum;
import com.charles.enums.Context;
import com.charles.enums.Events;
import com.charles.enums.States;
import com.charles.service.StatusAction;
import com.charles.service.StatusCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 短信推送活动状态机初始化
 */
@Component
public class SmsStateMachine implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private StatusAction smsStatusAction;
    @Autowired
    private StatusCondition smsStatusCondition;

    //基于DSL构建状态配置，触发事件转移和后续的动作
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        StateMachineBuilder<States, Events, Context> builder = StateMachineBuilderFactory.create();
        builder.externalTransition()
                .from(States.APPLY)
                .to(States.FIRST_TRIAL)
                .on(Events.SAVE_APPLICATION)
                .when(smsStatusCondition.checkNotifyCondition())
                .perform(smsStatusAction.doNotifyAction());
        builder.externalTransition()
                .from(States.FIRST_TRIAL)
                .to(States.FINAL_JUDGMENT)
                .on(Events.SUBMIT_APPLICATION)
                .when(smsStatusCondition.checkNotifyCondition())
                .perform(smsStatusAction.doNotifyAction());
        builder.externalTransition()
                .from(States.FINAL_JUDGMENT)
                .to(States.REMOVE)
                .on(Events.AUDIT_PASS)
                .when(smsStatusCondition.checkNotifyCondition())
                .perform(smsStatusAction.doNotifyAction());
        builder.build(StatusMachineEngine.getMachineEngine(ChannelTypeEnum.SMS));
    }
}